package com.library.system.modules.notice.service.impl;

import cn.hutool.core.util.StrUtil;
import com.library.common.enums.AuditStatusEnum;
import com.library.common.enums.ClassifyEnum;
import com.library.system.modules.examine.bo.ExamineInsert;
import com.library.system.modules.examine.service.ExamineService;
import com.library.system.modules.notice.entity.Notice;
import com.library.system.modules.notice.task.NoticeScheduler;
import com.library.system.modules.notice.vo.NoticeVO;
import com.library.system.modules.notice.bo.NoticePage;
import com.library.system.modules.notice.bo.NoticeInsert;
import com.library.system.modules.notice.mapper.NoticeMapper;
import com.library.system.modules.notice.struct.NoticeStructMapper;
import com.library.system.modules.notice.service.NoticeService;
import lombok.extern.log4j.Log4j2;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import jakarta.annotation.Resource;
import com.library.common.util.PageCovertUtil;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
import java.util.List;
import java.util.Objects;


/**
 * @Author xyh
 * @Desc 通知公告表(Notice)表服务实现类
 * @Date 2023-11-04 17:14:08
 */

@Log4j2
@Service("noticeService")
public class NoticeServiceImpl extends ServiceImpl<NoticeMapper, Notice> implements NoticeService {

    @Resource
    private NoticeStructMapper noticeStructMapper;
    @Resource
    private ThreadPoolTaskScheduler taskScheduler;
    @Lazy
    @Resource
    private ExamineService examineService;

    @Override
    public IPage<NoticeVO> queryByPage(NoticePage page) {
        // 查询条件
        LambdaQueryWrapper<Notice> queryWrapper = new LambdaQueryWrapper<>();
        if (page.getNoticeStatus() != null) {
            queryWrapper.eq(Notice::getNoticeStatus, page.getNoticeStatus());
        }
        if (StrUtil.isNotEmpty(page.getNoticeTitle())) {
            queryWrapper.like(Notice::getNoticeTitle, page.getNoticeTitle());
        }
        if (page.getNoticeType() != null) {
            queryWrapper.eq(Notice::getNoticeType, page.getNoticeType());
        }
        if (page.getUserId() != null) {
            queryWrapper.eq(Notice::getUserId, page.getUserId());
        }
        // 查询分页数据
        Page<Notice> noticePage = new Page<Notice>(page.getCurrent(), page.getSize());
        IPage<Notice> pageData = baseMapper.selectPage(noticePage, queryWrapper);

        //转换成vo
        IPage<NoticeVO> records = PageCovertUtil.pageVoCovert(pageData, NoticeVO.class);
        return records;
    }


    @Override
    public NoticeVO queryById(Integer id) {
        Notice notice = baseMapper.selectById(id);
        return noticeStructMapper.noticeToNoticeVO(notice);
    }

    @Override
    public boolean insertOrUpdate(NoticeInsert noticeInsert) {
        Notice notice = noticeStructMapper.insertToNotice(noticeInsert);
        if (noticeInsert.getId() != null) {
            //审核失败的公告才能修改
            updateById(notice);
        } else {
            save(notice);
        }
        //提交审核公告
        if (Objects.equals(notice.getNoticeType(), ClassifyEnum.NOTICE.getCode())) {
            noticeExamine(notice, ClassifyEnum.NOTICE);
        }
        if (notice.getSendTime() != null) {
            taskScheduler.schedule(new NoticeScheduler.NoticeTaskSender(notice, this), Date.from(notice.getSendTime().atZone(ZoneId.systemDefault()).toInstant()));
        }
        return true;
    }

    private void noticeExamine(Notice notice, ClassifyEnum classifyEnum) {
        ExamineInsert examineInsert = new ExamineInsert();
        examineInsert.setTitle(notice.getNoticeTitle());
        examineInsert.setContent(notice.getNoticeContent());
        examineInsert.setClassifyId(notice.getId());
        examineInsert.setSubmitUsername(notice.getUserName());
        examineService.insertExamine(examineInsert, classifyEnum);
        log.info("通知公告已提交审核，审核标题：{}", notice.getNoticeTitle());
    }

    @Override
    public boolean deleteById(Integer id) {
        return removeById(id);
    }

    @Override
    public List<Notice> getNoticeSendTime() {
        return lambdaQuery().eq(Notice::getNoticeStatus, AuditStatusEnum.TIME_SEND.getCode()).list();
    }

    @Override
    public void cancelNoticeTime(Integer id) {
        Notice notice = getById(id);
        if (notice.getSendTime() != null) {
            if (AuditStatusEnum.TIME_SEND.getCode().equals(notice.getNoticeStatus())) {
                notice.setNoticeStatus(AuditStatusEnum.SEND_SUCCESS.getCode());
            } else {
                notice.setNoticeStatus(AuditStatusEnum.CANCEL_TIME.getCode());
            }
        }
        baseMapper.updateById(notice);
        log.info("取消定时成功，公告id为：{}", id);
    }

    @Override
    public void updateNoticeStatus(Integer id, AuditStatusEnum statusEnum, String result) {
        Notice notice = getById(id);
        if (notice != null) {
            if (AuditStatusEnum.AUDIT_SUCCESS.getCode().equals(statusEnum.getCode())) {
                if (notice.getSendTime() != null) {
                    notice.setNoticeStatus(AuditStatusEnum.TIME_SEND.getCode());
                } else {
                    notice.setNoticeStatus(AuditStatusEnum.SEND_SUCCESS.getCode());
                }
            } else {
                notice.setNoticeStatus(statusEnum.getCode());
            }
            notice.setResult(result);
            notice.setFinishTime(LocalDateTime.now());
            updateById(notice);
        }
    }

}
